import React, { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { Button, Popconfirm, Form, Radio, App, Drawer, Space, Image } from 'antd'
import { useModel } from '@umijs/max'
import { PlusOutlined } from '@ant-design/icons'
import copy from 'copy-to-clipboard'
import dayjs from 'dayjs'
import styles from './Coupon.less'

export default () => {
  const { CouponList, DeleteCoupon, SetCouponOver, CouponOrderList } = useModel('Coupon')
  const { wxGenerateScheme } = useModel('Order')
  const { platformInfo } = useModel('Global')
  const { GetShowPlts } = useModel('ProductCategory')
  const [linkTypeForm] = Form.useForm()

  const { message, modal } = App.useApp()

  const tableRef = useRef()
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量
  const [linkTypeList, setLinkTypeList] = useState(10) //  每页数量

  const [currentId, setCurrentId] = useState(null)
  const [orderListFlag, setOrderListFlag] = useState(false)

  useEffect(() => {
    getPlatsList()
  }, [])

  const getPlatsList = async () => {
    const res = await GetShowPlts()
    if (res) {
      let list = Object.keys(res).map(i => ({
        label: res[i],
        value: res[i]
      }))
      if (!platformInfo.h5_url) {
        list = list
          .map(i => {
            if (i.value === 'H5' || i.value === 'APP') {
              return null
            } else {
              return i
            }
          })
          .filter(i => i)
      }
      if (list && list[0]) {
        linkTypeForm.setFieldsValue({
          type: list[0].value
        })
      }
      setLinkTypeList(list)
    }
  }

  // 新增/编辑增值服务
  const handleAddAndEdit = async (type, row) => {
    let url = `/couponDetail?type=${type}`
    if (type !== 'add' && row?.id) {
      url += `&id=${row.id}`
    }
    window.open(url)
  }

  // 结束
  const handleClose = row => {
    modal.confirm({
      title: '停止优惠券确认',
      content:
        '操作停止后，无法继续编辑优惠券内容；用户无法再领取该优惠券（之前已领取的优惠券，在有效期内仍可继续使用），是否确认停止？',
      okButtonProps: {
        type: 'primary'
      },
      okType: 'danger',
      onOk: async () => {
        let params = {
          id: row.id
        }
        const res = await SetCouponOver(params)
        if (res) {
          message.success('操作成功')
          tableRef.current.reload()
        }
      }
    })
  }

  const handleDelete = async row => {
    let params = {
      id: row.id
    }
    const res = await DeleteCoupon(params)
    if (res) {
      message.success('操作成功')
      tableRef.current.reload()
    }
  }

  const generateWXLink = async (id, close) => {
    const res = await WxGenerateScheme({
      path: `/pages/receiveCoupon/receiveCoupon`,
      query: `couponId=${id}`
    })
    copy(res)
    message.success('微信跳转链接已生成并复制至剪贴板')
    await close()
  }

  const handleFinish = async (close, row) => {
    if (linkTypeList && linkTypeList.length) {
      const res = await linkTypeForm.validateFields()
      if (res) {
        const { type } = res
        switch (type) {
          case '支付宝':
            const aliLink = `https://ulink.alipay.com/?scheme=alipays://platformapi/startapp?appId=${
              platformInfo.ali_appid
            }${encodeURIComponent(
              `&page=pages/receiveCoupon/receiveCoupon?couponId=${row.id}`
            )}\r\n请复制链接到浏览器打开
            `
            copy(aliLink)
            message.success('支付宝跳转链接已生成并复制至剪贴板')
            await close()
            break
          case 'H5':
            const h5Link = `https://${platformInfo.h5_url}/pages/receiveCoupon/receiveCoupon?couponId=${row.id}`
            copy(h5Link)
            message.success('H5跳转链接已生成并复制至剪贴板')
            await close()
            break
          case '微信':
            await generateWXLink(row.id, close)
            break
          default:
            console.log('type', type)
            break
        }
      }
    } else {
      await close()
    }
  }

  const generateLink = row => {
    modal.confirm({
      title: '生成优惠券链接',
      icon: null,
      okButtonProps: {
        type: 'primary'
      },
      okCancel: true,
      content: (
        <>
          {linkTypeList && linkTypeList.length ? (
            <Form name='linkType' form={linkTypeForm}>
              <Form.Item name='type' label='生成链接类型' rules={[{ required: true, message: '请选择生成链接类型' }]}>
                <Radio.Group>
                  {linkTypeList.map(item => {
                    return (
                      <Radio value={item.value} key={item.value}>
                        {item.value}
                      </Radio>
                    )
                  })}
                </Radio.Group>
              </Form.Item>
            </Form>
          ) : (
            '暂无可用的渠道，请联系运营人员'
          )}
        </>
      ),
      onOk: close => {
        handleFinish(close, row)
      }
    })
  }

  const triggerOrderListDrawer = () => {
    setOrderListFlag(!orderListFlag)
  }

  const triggerOrderList = async id => {
    setCurrentId(id)
    setOrderListFlag(true)
  }

  // 跳转商品页
  const goProduct = (type, id, merchant_id) => {
    let url = `/product?type=${type}&id=${id}&merchant_id=${merchant_id}`
    window.open(url)
  }

  const columns = [
    {
      title: '优惠券信息',
      dataIndex: 'coupon_name',
      // width: 240,
      hideInSearch: true,
      render: (text, record) => {
        return (
          <>
            <div>
              <b>{text}</b>
            </div>
            <div>券ID：{record.id}</div>
          </>
        )
      }
    },
    {
      title: '名称',
      dataIndex: 'coupon_name',
      hideInTable: true
    },

    {
      title: '推广方式',
      dataIndex: 'show_type',
      width: 100,
      align: 'center',
      valueEnum: {
        1: '自动推广',
        2: '私域链接'
      }
    },
    {
      title: '类型',
      dataIndex: 'deduct_type',
      width: 100,
      align: 'center',
      valueEnum: {
        1: '下单立减'
      }
    },
    {
      title: '优惠内容',
      dataIndex: 'content_text',
      hideInSearch: true,
      width: 300,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status_text',
      width: 120,
      hideInSearch: true,
      align: 'center',
      valueEnum: {
        未开始: {
          text: '未开始',
          status: 'Default'
        },
        进行中: {
          text: '进行中',
          status: 'Processing'
        },
        已结束: {
          text: '已结束',
          status: 'Error'
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      hideInTable: true,
      align: 'center',
      valueEnum: {
        not_start: '未开始',
        running: '进行中',
        over: '已结束'
      }
    },

    {
      title: '可用时间',
      dataIndex: 'use_start_at',
      width: 240,
      hideInSearch: true,
      align: 'center',
      render: (_, row) => (
        <>
          <div>起：{_}</div>
          <div>止：{row.use_end_at}</div>
        </>
      )
    },

    {
      title: '领取量',
      dataIndex: 'receive_num',
      width: 120,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '发放量',
      dataIndex: 'send_num',
      width: 120,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '已使用',
      dataIndex: 'used_num',
      width: 120,
      align: 'center',
      hideInSearch: true
    },

    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 200,
      align: 'center',
      valueType: 'dateTimeRange',
      render: (_, record) => <div>{record.created_at}</div>,
      search: {
        transform: value => {
          return {
            start: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            end: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    },

    {
      title: '可用时间',
      dataIndex: 'use_at',
      width: 100,
      align: 'center',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: value => {
          return {
            start: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            end: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    },

    {
      title: '订单数据',
      dataIndex: 'today_order_amount',
      width: 200,
      hideInSearch: true,
      align: 'center',
      render: (_, row) => (
        <>
          <div>总和：¥{row.order_amount || '0.00'}</div>
          <div>今日：¥{_}</div>
          <Button type='primary' onClick={() => triggerOrderList(row.id)}>
            订单信息
          </Button>
        </>
      )
    },
    {
      title: '优惠数据',
      dataIndex: 'today_deduct_money',
      width: 200,
      hideInSearch: true,
      align: 'center',
      render: (_, row) => (
        <>
          <div>总和：¥{row.total_deduct_money || '0.00'}</div>
          <div>今日：¥{_}</div>
        </>
      )
    },

    {
      title: '操作',
      key: 'option',
      width: 280,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        let { is_ended, can_delete, show_type } = row
        return (
          <>
            <Button type='link' key='check' onClick={() => handleAddAndEdit('check', row)}>
              查看
            </Button>
            <Button type='link' key='edit' onClick={() => handleAddAndEdit('edit', row)}>
              编辑
            </Button>
            {/* {show_type === 2 ? ( */}
            <Button type='link' key='link' onClick={() => generateLink(row)}>
              链接
            </Button>
            {/* ) : null} */}
            {!is_ended ? (
              <Button onClick={() => handleClose(row)} type='link' danger>
                结束
              </Button>
            ) : null}
            {can_delete ? (
              <Popconfirm
                key='delete'
                title='确定删除吗?'
                onConfirm={() => handleDelete(row)}
                okText='确认'
                cancelText='取消'
              >
                <Button type='link' danger>
                  删除
                </Button>
              </Popconfirm>
            ) : null}
          </>
        )
      }
    }
  ]

  const orderInfoColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48
    },
    {
      title: '订单信息',
      dataIndex: 'order_sn',
      width: 200,
      hideInSearch: true,
      render: (_, row) => (
        <>
          <div>订单编号：{_}</div>
          <div>下单时间：{row.created_at}</div>
        </>
      )
    },
    {
      title: '商品信息',
      dataIndex: 'goods_pic',
      hideInSearch: true,
      width: 200,
      render: (text, record) => (
        <Space>
          <Image width={48} src={text} />
          <div>
            <a onClick={() => goProduct(3, record.goods_id, record.merchant_id)}>{record.goods_name}</a>
            <div>{record.attr_value}</div>
          </div>
        </Space>
      )
    },
    {
      title: '优惠券信息',
      dataIndex: 'coupon_name',
      width: 200,
      hideInSearch: true,
      render: (text, row) => (
        <>
          <div>
            <b>{text}</b>
          </div>
          <div>券ID：{row.coupon_id}</div>
        </>
      )
    },
    {
      title: '客户信息',
      dataIndex: 'cert_name',
      hideInSearch: true,
      width: 120,
      render: (text, row) => (
        <>
          <div>姓名：{text}</div>
          <div>手机号：{row.tel}</div>
          <div>身份证：{row.cert_no}</div>
          <div>人脸识别：{row.face_status_text}</div>
        </>
      )
    },
    {
      title: '订单状态',
      dataIndex: 'status_text',
      hideInSearch: true,
      width: 120
    },
    {
      title: '租金信息',
      width: 200,
      dataIndex: 'total_price',
      hideInSearch: true,
      render: (text, row) => (
        <>
          <div>
            <b>总租金：{text}</b>
          </div>
          <div>当前买断款：{row.current_buyout_to_pay}</div>
        </>
      )
    },
    {
      title: '客户姓名',
      dataIndex: 'user_name',
      hideInTable: true,
      width: 120
    },
    {
      title: '订单编号',
      dataIndex: 'order_sn',
      hideInTable: true,
      width: 120
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      hideInTable: true,
      width: 120
    },
    {
      title: '下单时间',
      dataIndex: 'created_at',
      hideInTable: true,
      valueType: 'dateTimeRange',
      width: 120,
      search: {
        transform: value => {
          return {
            start: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            end: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    }
  ]

  return (
    <>
      <ProTable
        actionRef={tableRef}
        request={async params => {
          const filters = {
            shop_name: params.shop_name,
            contact_tel: params.contact_tel,
            legal_person_name: params.legal_person_name,
            status: params.status,
            created_at_start: params.start,
            created_at_end: params.end
          }

          const param = {
            page: params.current,
            page_size: params.pageSize,
            ...filters
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)

          const res = await CouponList(param)

          return {
            data: res.data,
            success: true,
            total: res.total
          }
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        rowKey='id'
        scroll={{ x: 'max-content' }}
        columns={columns}
        headerTitle={
          <Button
            icon={<PlusOutlined />}
            key={Math.random().toString()}
            type='primary'
            onClick={() => handleAddAndEdit('add')}
          >
            新建优惠券
          </Button>
        }
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
          span: 6
        }}
      />

      {/*订单信息抽屉*/}
      <Drawer
        title='订单信息'
        placement='right'
        className={styles.goods_drawer_wrapper}
        onClose={triggerOrderListDrawer}
        open={orderListFlag}
        width={1480}
        destroyOnClose
        footer={
          <div className={styles.drawer_footer}>
            <Space>
              <Button onClick={triggerOrderListDrawer}>关闭</Button>
            </Space>
          </div>
        }
      >
        <ProTable
          search={{
            defaultCollapsed: false,
            labelWidth: 75,
            span: 6
          }}
          request={async params => {
            const param = {
              coupon_id: currentId,

              user_name: params.user_name,
              order_sn: params.order_sn,
              tel: params.tel,
              created_at_start: params.start,
              created_at_end: params.end
            }
            const res = await CouponOrderList(param)
            return {
              data: res.data,
              success: true,
              total: res.total
            }
          }}
          pagination={{
            pageSize: 10
          }}
          options={false}
          rowKey='order_id'
          columns={orderInfoColumns}
        />
      </Drawer>
    </>
  )
}
